package com.xiaotu.common.aop;

import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.xiaotu.common.exception.SpiderException;
import com.xiaotu.common.exception.SpiderExceptionCode;
import com.xiaotu.common.model.JobLogModel;
import com.xiaotu.common.model.SpiderLogModel;
import com.xiaotu.common.util.Constants;
import com.xiaotu.common.util.GsonUtils;
import com.xiaotu.spider.AHttpProcessor;

import net.sf.json.JSONObject;
import us.codecraft.webmagic.ResultItems;

/**
 * @类名 ClientResponseAspect
 * @日期 2015年5月28日
 * @作者 高海军
 * @功能 针对具体对象的爬虫采集任务日志切面
 */
public class HttpProcessLogAspect extends ALogAspect
{
	
	private static final Logger LOGGER = LoggerFactory
			.getLogger(HttpProcessLogAspect.class);
	
	/**
	 * 对HttpProcessor的process方法进行横切，调用方法前后都做相应的异常处理
	 * @param joinPoint 连接点
	 */
	@SuppressWarnings("unchecked")
	public void aroundMethod(ProceedingJoinPoint joinPoint)
	{
		JobLogModel logModel = new JobLogModel();
		try
		{
			
			if (!(joinPoint.getTarget() instanceof AHttpProcessor))
				throw new SpiderException(
						SpiderExceptionCode.HttpProcessorClassErrorException);
			
			AHttpProcessor processor = (AHttpProcessor) joinPoint.getTarget();
			
			SpiderLogModel taskLog = processor.getSpiderLog();// 获取整个任务基本信息
			if (taskLog == null)
				throw new SpiderException(
						SpiderExceptionCode.SpiderTaskInfoErrorException);
			
			logModel.setSeriesNo(taskLog.getSeriesNo());
			logModel.setJobType(processor.getSpiderType());
			logModel.setDataType(processor.getPageDataType());
			
			Object[] args = joinPoint.getArgs();
			if (args == null || args.length < 2
					|| !(args[0] instanceof JSONObject)
					|| !(args[1] instanceof ResultItems))
				throw new SpiderException(
						SpiderExceptionCode.PageProcessorParameterErrorException);
			JSONObject target = (JSONObject) args[0];
			
			setLogInfo(target, logModel);// 记录爬取对象的基本信息
			joinPoint.proceed();// 处理爬取的数据
			
			logModel.setTargetContent(
					GsonUtils.toJson(((ResultItems) args[1]).getAll()));
			if (StringUtils.isEmpty(logModel.getJobStatus()))
				logModel.setJobStatus(Constants.JobStatus.SUCCESS);
		}
		catch (SpiderException e)
		{
			LOGGER.error("[{}] http processor error:", logModel.getJobType(),
					e);
			if (SpiderExceptionCode.DataInvalideException
					.equals(e.getExceptionCode()))
				logModel.setJobStatus(Constants.JobStatus.INVALIDE);
			else
				logModel.setJobStatus(Constants.JobStatus.FAIL);
			logModel.setException(e.getExceptionCode().toString());
			logModel.setMessage(e.getMessage());
		}
		catch (Throwable e)
		{
			LOGGER.error("[{}] http processor error", logModel.getJobType(), e);
			logModel.setJobStatus(Constants.JobStatus.FAIL);
			logModel.setException(e.getClass().getSimpleName());
			logModel.setMessage(e.getMessage());
		}
		finally
		{
			logModel.setTimestamp(System.currentTimeMillis());
			if (LOGGER.isDebugEnabled())
				LOGGER.debug("[{}] http processor Log:{}", logModel.getJobType(),
						GsonUtils.toJson(logModel));
			this.saveLog(logModel);
		}
	}
}